<template>
	<!-- v-if="loaded" -->
	<view v-if="loaded" :id="templateId" class="container">
		<!-- 商品区域 begin -->
		<view class="goods-wrap">
			<uni-goods-col
				:key="index"
				:goods="bargainData.goodsDetail"
				:routeLink="
					`/pages/common/pages/goods/goodsDetail?goodsId=${bargainData.goodsDetail.goodsId}`
				"
				:goodsPrice="bargainData.goodsDetail.priceStr.split('.')"
				:latePrice="bargainData.goodsDetail.priceOut"
				:priceColor="themeStyles.mainColor"
				:goodsTypeText="bargainData.goodsDetail.skuName"
			>
				<template slot="metaRight">
					<view class="goods-num"
						>已砍{{
							bargainData.goodsDetail.successGoodsNum || 0
						}}</view
					>
				</template>
			</uni-goods-col>
		</view>
		<!-- 商品区域 end -->

		<!-- 砍价状态 begin -->
		<view class="bargain-wrap">
			<view class="status-wrap">
				<!-- 倒计时区域 begin -->
				<view
					v-if="
						bargainData.myBargain === 1 ||
							(bargainData.myBargain === 2 &&
								currentBargainStatus('1101'))
					"
					class="countdown"
				>
					<view class="countdown-prompt">
						<text class="line"></text>
						<text class="title">
							<template v-if="currentBargainStatus('1101')">
								砍价
							</template>
							<template v-else>
								付款
							</template>
							剩余时间</text
						>
						<text class="line"></text>
					</view>
					<uni-countdown
						splitorColor="#666666"
						:color="themeStyles.auxiliaryColor"
						:bgColor="themeStyles.mainColor"
						:show-day="false"
						:hour="bargainData.countdown.hh"
						:minute="bargainData.countdown.mm"
						:second="bargainData.countdown.ss"
					>
					</uni-countdown>
				</view>
				<!-- 倒计时区域 end -->

				<template>
					<!-- 砍价进度条 begin -->
					<template v-if="currentBargainStatus('1101')">
						<view class="step-wrap">
							<view class="title">
								<text
									>已砍<text
										:style="themeStyles.textAdronmentColor"
										class="price"
										>{{ bargainData.downPrice }}</text
									>元，还差<text
										:style="themeStyles.textAdronmentColor"
										class="price"
										>{{ bargainData.shortPrice }}</text
									>元</text
								>
							</view>
							<view class="status-box">
								<view class="por step-box">
									<view
										class="poa step"
										:style="{
											width: `${bargainData.progress}%`,
											background: `linear-gradient(to right, ${themeStyles.adronmentColor}66, ${themeStyles.adronmentColor})`
										}"
									></view>
								</view>
							</view>
						</view>
					</template>
					<!-- 砍价进度条 end -->

					<!-- 砍价完成图片区域 begin -->
					<template v-else>
						<view class="image-wrap">
							<image
								:class="
									bargainData.myBargain === 1
										? 'image'
										: 'image-large'
								"
								:src="
									baseTemplateFileUri +
										'image/activity/complete.png'
								"
							></image>
						</view>
					</template>
					<!-- 砍价完成图片区域 end -->
				</template>

				<view class="tac already-status">
					<template v-if="bargainData.myBargain === 1">
						<template v-if="currentBargainStatus('1201')">
							恭喜您，砍掉<text
								:style="themeStyles.textAdronmentColor"
								class="price"
								>{{ bargainData.downPrice || 0 }}</text
							>元
						</template>
					</template>
					<template v-else>
						<template
							v-if="
								bargainData.bhdb && currentBargainStatus('1101')
							"
						>
							帮忙砍掉<text
								:style="themeStyles.textAdronmentColor"
								class="price"
								>{{ bargainData.bhdb.money || 0 }}</text
							>元
						</template>
						<template v-else-if="currentBargainStatus('1202')">
							砍价完成！成功砍掉<text
								:style="themeStyles.textAdronmentColor"
								class="price"
								>{{ bargainData.downPrice || 0 }}</text
							>元
						</template>
					</template>
				</view>

				<!-- 完成砍价 end -->

				<view class="df jc-sb ai-c btn-group">
					<template v-if="bargainData.myBargain === 1">
						<template v-if="currentBargainStatus('1101')">
							<button
								open-type="share"
								:style="themeStyles.btnFullColor"
								class="bargain-btn bargain-btn-full"
							>
								邀好友砍价
							</button>

							<button
								@click="showPop = true"
								:style="themeStyles.btnAuxiliaryColor"
								class="bargain-btn"
							>
								现价购买
							</button>
						</template>
						<button
							v-else-if="currentBargainStatus('1201')"
							@click="nowPay()"
							:style="themeStyles.btnFullColor"
							class="bargain-btn bargain-btn-full bargain-btn-large"
						>
							立即付款
						</button>
					</template>
					<template v-else>
						<template
							v-if="
								!bargainData.bhdb.money &&
									currentBargainStatus('1101')
							"
						>
							<template>
								<button
									v-if="hasLogin"
									@click.stop="onHlepBargain()"
									:style="themeStyles.btnFullColor"
									class="bargain-btn bargain-btn-full"
								>
									帮忙砍价
								</button>
								<button
									v-else
									open-type="getUserInfo"
									@getuserinfo="loginHelpBargain"
									:style="themeStyles.btnFullColor"
									class="bargain-btn bargain-btn-full"
								>
									帮忙砍价
								</button>
							</template>
							<button
								v-if="currentBargainStatus('1101')"
								@click.stop="alsoBuy()"
								:style="themeStyles.btnAuxiliaryColor"
								class="bargain-btn"
							>
								我也要买
							</button>
						</template>
						<button
							v-else-if="
								bargainData.bhdb.money ||
									currentBargainStatus('1202')
							"
							@click.stop="alsoBuy()"
							:style="themeStyles.btnAuxiliaryColor"
							class="bargain-btn bargain-btn-large"
						>
							我也要买
						</button>
					</template>
				</view>
			</view>

			<!-- 帮砍用户列表 begin -->
			<view class="people-wrap">
				<trick-title
					title="砍价记录"
					iconName="bargain-full"
					:color="themeStyles.mainColor"
					:iconColor="themeStyles.lightMainColor"
				>
				</trick-title>
				<view class="people-list">
					<view
						v-for="(item, index) in helpPeople"
						:key="index"
						class="people-item"
					>
						<view class="people-info">
							<image :src="item.headImage" class="img"></image>
							<text class="clamp username">{{
								item.nickname
							}}</text>
						</view>
						<view class="cut-price-box">
							<image
								:src="
									baseTemplateFileUri +
										'image/activity/cut.png'
								"
								class="cut-img"
							></image>
							<text class="cut-price"
								>砍掉{{ item.money || 0 }}元</text
							>
						</view>
					</view>
				</view>
			</view>
			<!-- 帮砍用户列表 end -->
		</view>
		<!-- 砍价状态 end -->

		<!-- 弹出层 begin -->
		<!-- v-if="showPop" -->
		<view v-if="showPop" class="df df-c pop-wrap">
			<!-- 砍价 begin -->
			<view class="prompt-box">
				<!-- 发起人现价购买 begin -->
				<template v-if="bargainData.myBargain === 1">
					<view class="prompt-content">
						<view class="prompt-title">确定以现价购买吗?</view>
						<view class="prompt-txt">
							现价
							<text
								:style="themeStyles.textAdronmentColor"
								class="price"
								>{{ bargainData.nowPrice }}</text
							>
							还可以再砍
							<text
								:style="themeStyles.textAdronmentColor"
								class="price"
								>{{ bargainData.shortPrice }}</text
							>
							元！
						</view>
						<image
							:src="
								baseTemplateFileUri +
									'image/activity/current.png'
							"
							class="prompt-image"
						></image>
					</view>
					<view class="df jc-sb ai-c btn-group">
						<button
							@click="showPop = false"
							:style="themeStyles.btnFullColor"
							class="df df-c btn btn-full"
						>
							继续砍价
						</button>
						<button
							@click="showPop = false;nowPay()"
							:style="themeStyles.btnAuxiliaryColor"
							class="df df-c btn"
						>
							确定购买
						</button>
					</view>
				</template>
				<!-- 发起人现价购买 end -->
				<!-- 帮砍人显示 begin -->
				<template v-else>
					<view class="prompt-content">
						<view class="prompt-title">砍价成功</view>
						<view class="prompt-txt">
							<view class="tac going-title"
								>帮忙砍掉了<text
									:style="themeStyles.textAdronmentColor"
									class="price"
									>{{ bargainData.bhdb.money }}</text
								>
								元</view
							>
						</view>
						<image
							:src="
								baseTemplateFileUri +
									'image/activity/complete.png'
							"
							class="prompt-image"
						></image>
					</view>
					<view class="df jc-c ai-c btn-group">
						<button
							@click="alsoBuy()"
							:style="themeStyles.btnFullColor"
							class="df df-r btn btn-large btn-full"
						>
							我也要购买
						</button>
					</view>
				</template>
				<!-- 帮砍人显示 end -->
			</view>

			<!-- 取消按钮 begin -->
			<image
				@click="showPop = false"
				:src="baseTemplateFileUri + 'image/activity/cancel.png'"
				class="cancel"
			></image>
			<!-- 取消按钮 end -->

			<!-- 砍价 end -->
		</view>
		<!-- 弹出层 end -->
		<!-- 选择支付方式弹层 -->
		<pop-pay
			type="10"
			:showPopPay="showPopPay"
			:orderInfo="bargainData"
			@close="closePopPay"
			@select-pay-type="selectPayMoneyTypeAfter"
			@payBefore="callPayBefore"
			@payFn="callPay"
			@paySuccessAfter="paySuccessAfter"
			@payFailAfter="payFailAfter"></pop-pay>
	</view>
</template>

<script>
/** components begin */
import uniCountdown from "@/components/uniCountdown/uniCountdown";
import uniGoodsCol from "@/components/goods/uniGoodsCol";
import trickTitle from "@/components/trickTitle/trickTitle";
/** components end */

/** api begin */
import {
	queryBargainDetail,
	addBargainOrder
} from "@/lib/api/bargainServer/initiator";
import {
	helpBargain,
	queryHelpBargainPeople
} from "@/lib/api/bargainServer/help";
/** api end */
/* 选择支付方式弹层 */
import popPay from "@/components/popPay";
import loginMixin from "@/mixins/login";
import payMixin from "@/mixins/pay";
export default {
	mixins: [loginMixin, payMixin],
	components: {
		uniCountdown,
		uniGoodsCol,
		trickTitle,
		popPay
	},

	data() {
		return {
			joinId: "",
			helpPeople: [],
			bargainData: {
				goodsDetail: {
					priceStr: "" // 给默认值，防止报错
				}
			},
			showPop: false,
			timer: null
		};
	},

	onLoad(option) {
		this.joinId = option.joinId;
		// this.joinId = "424c2877a5474cfe9202b6a4c4cda643";
	},

	async onShow() {
		uni.showLoading({ title: "加载中" });
		clearInterval(this.timer && this.timer);
		await this.initLoading();
		this.loaded = true;
		uni.hideLoading();
		this.timer = setInterval(() => {
			this.initLoading();
		}, 5000);
	},

	onHide() {
		clearInterval(this.timer && this.timer);
	},

	onUnload() {
		clearInterval(this.timer && this.timer);
	},

	onShareAppMessage(res) {
		return {
			title: "我发现一件好货，来帮我一起砍价吧",
			path: `/pages/activity/pages/bargain?this.joinId=${this.this.joinId}`
		};
	},

	methods: {
		async initLoading() {
			try {
				await this.getBargin();
				await this.getHlepPeople();
			} catch (error) {
				console.log("error", error);
				await this.$api.showToast(error.resultInfo || "加载失败");
				uni.navigateBack();
			}
		},
		// 登录砍价
		async loginHelpBargain(e) {
			try {
				await this.login(e);
				console.log("error", error);
			} catch (error) {
				this.$api.showToast(error.resultInfo || "登录失败");
				return;
			}

			this.onHlepBargain();
		},

		async onHlepBargain() {
			try {
				await this.doHelpBargain();
				await this.getBargin();
				this.showPop = true;
			} catch (error) {
				console.log("error", error);
				this.$api.showToast(error.resultInfo || "操作失败");
			}
		},

		alsoBuy() {
			uni.redirectTo({
				url: `/pages/activity/pages/activityList?activityType=20`
			});
		},

		// 帮砍价
		doHelpBargain() {
			const propsData = {
				bargainInitiatorId: this.bargainData.bargainInitiatorId
			};
			return helpBargain(propsData);
		},
		//  支付之前
		async callPayBefore(val,callback){
			if(!this.orderId){
				try {
					this.orderId =
						this.bargainData.orderId ||
						(await this.createBargainOrder());
				} catch (error) {
					console.log("error", error);
					//await this.$api.showToast(error.resultInfo || "操作失败");
				}
			}
			//
			callback(this.orderId);
		},
		// 开始支付
		async callPay(val,callback){
			let payInfo;
			try {
				payInfo = await this.onPay(this.orderId,this.payMoneyType);
				//uni.redirectTo({ url: "/pages/user/pages/order/orderList" });
			} catch (error) {
				console.log("error", error);
				//this.$api.showToast(error.resultInfo || "支付失败");
				//uni.redirectTo({ url: "/pages/user/pages/order/orderList" });
			}
			//支付之后
			callback(payInfo);
		},
		// 付款成功之后
		paySuccessAfter(){
			//到店订单15 or 线上订单10   
			let orderType = this.bargainData.type;
			let orderStatus = orderType===10?4:3;
			uni.redirectTo({
				url: `/pages/user/pages/order/orderList?orderStatus=${orderStatus}`
			});
		},
		//  支付失败之后
		payFailAfter(){
			let orderStatus = 1;
			uni.redirectTo({
				url: `/pages/user/pages/order/orderList?orderStatus=${orderStatus}`
			});
		},
		// 付款
		async nowPay(status) {
			// 打开支付弹层
			this.openPopPay();
			//
			//   if (status === 1) {
			//     // const modalRes = await this.$api.showModal({
			//     //     content: `是否以现价${this.bargainData.price}元购买`,
			//     //     showCancel: true
			//     // });
			//     // if(!modalRes.confirm) {
			//     //     await this.$api.showToast('操作已取消');
			//     //     return;
			//     // }
			//     try {
			//       await this.$api.showModal({
			//         content: `是否以现价${this.bargainData.price}元购买`,
			//         showCancel: true
			//       });
			//     } catch (error) {
			//       await this.$api.showToast("操作已取消");
			//       return;
			//     }
			//   }

			/* let orderId = "";
			try {
				orderId =
					this.bargainData.orderId ||
					(await this.createBargainOrder());
			} catch (error) {
				console.log("error", error);
				await this.$api.showToast(error.resultInfo || "操作失败");
				return;
			} */

			/* try {
				await this.onPay(orderId);
				uni.redirectTo({ url: "/pages/user/pages/order/orderList" });
			} catch (error) {
				console.log("error", error);
				this.$api.showToast(error.resultInfo || "支付失败");
				uni.redirectTo({ url: "/pages/user/pages/order/orderList" });
			} */
		},

		buyOtherGoods() {
			uni.switchTab({
				url: `/pages/tabbar/category`
			});
		},

		// 创建付款订单
		createBargainOrder() {
			const propsData = {
				bargainInitiatorId: this.bargainData.bargainInitiatorId
			};

			return addBargainOrder(propsData).then(res => {
				return res.data.orderId;
			});
		},
		// 获取砍价详情
		getBargin() {
			const propsData = {
				showLoading: false,
				bargainInitiatorId: this.joinId
			};
			console.log("propsData", propsData);
			return queryBargainDetail(propsData).then(res => {
				res.data.goodsDetail.price = res.data.goodsDetail.priceStr.split(
					"."
				);
				this.bargainData = res.data;
				console.log("this.bargainData", this.bargainData);
			});
		},

		async getHlepPeople() {
			const propsData = {
				showLoading: false,
				bargainInitiatorId: this.joinId
			};
			try {
				const res = await queryHelpBargainPeople(propsData);
				this.helpPeople = res.data.list;
			} catch (error) {
				console.log("error", error);
				this.$api.showToast(error.resultInfo || "操作失败");
			}
		},

		/**
		 * @param { String } type // 按钮类型 1101: 进行中 1201: 已完成
		 */
		currentBargainStatus(type) {
			const bargainStatus = this.bargainData.bargainStatus; // 砍价状态 0: 去砍价 1: 去下单 2: 去付款 3: 已结束
			const processing = bargainStatus === 0;
			const complete = bargainStatus === 1 || bargainStatus === 2;
			const over = bargainStatus === 3;
			let showBtn = false;
			switch (type) {
				case "1101":
					showBtn = processing;
					break;
				case "1201":
					showBtn = complete;
					break;
				case "1202": // 砍价结束（失败/成功）
					showBtn = complete || over;
					break;

				default:
					break;
			}
			return showBtn;
		}
	}
};
</script>

<style lang="scss" scoped>
@import "@/pages/activity/styles/bargain.scss";
</style>
